package com.qunar.wan.web.controller;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.qunar.wan.common_api.model.*;
import com.qunar.wan.common_api.serializer.RowBounds;
import com.qunar.wan.common_api.service.*;
import com.qunar.wan.util.HTMLTagsUtil;
import com.qunar.wan.util.HttpServletUtil;
import com.qunar.wan.web.controller.common.AbstractController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * User: cyoung Date: 11/27/13 Time: 3:28 PM
 */
@Controller
@RequestMapping("/activity")
public class SearchController extends AbstractController  {
    private Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Resource
    private ActivityService activityService;
    @Resource
    private LuceneSearchService activitySearchService;
    @Resource
    private UserService userService;
    @Resource
    private UserClassifyService userClassifyService;


    @RequestMapping(value = "/search")
    @ResponseBody
    public Object search(@RequestParam String keywords,
                         @RequestParam(defaultValue = "10", required = false) int pageSize,
                         @RequestParam(defaultValue = "1", required = false) int page, HttpServletRequest request) throws Exception {
        long start = System.currentTimeMillis();
//        keywords = URLDecoder.decode(keywords, "UTF-8");
        keywords = new String(keywords.getBytes("ISO-8859-1"),"UTF-8");
        /** 记录用户搜索信息，便于以后推送（虽然不在此次需求） */
        String username =userService.currentLogonUser() == null ? null:userService.currentLogonUser().getUserName();
        String userinfo = null == username ? HttpServletUtil.getClientIp(request) : username;
        logger.info("用户{}搜索\"{}\",第{}页", userinfo, keywords, page);
        SearchResult result = activitySearchService.search(keywords, pageSize, page);
        if (result == null) {
            List<Activity> recommend = new ArrayList<Activity>(5);
            if (StringUtils.isEmpty(username)) {
                return dataJson("暂未找到符合条件的数据", System.currentTimeMillis() - start).put("recommend", Arrays.asList());
            }
            /** 搜索结果为空时，根据用户关注推荐部分活动，数量为5 */
            List<SubClassify> userSubclassifies = userClassifyService.selectByuserId(userService.selectUserByName(
                    username).getId());
            if (userSubclassifies.isEmpty()) {
                return dataJson("暂未找到符合条件的数据", System.currentTimeMillis() - start);
            }
            for (SubClassify subClassify : userSubclassifies) {
                if (recommend.size() >= 5) {
                    break;
                }
                recommend.addAll(activityService.selectByClassify(0, subClassify.getId(), false, new RowBounds(0, 1)));
            }
            return dataJson("", System.currentTimeMillis() - start).put("recommend", convert2Index(recommend));
        }
        return dataJson(result.getIndexLists(), System.currentTimeMillis() - start).put("totalPage",
                result.getTotalPage()).put("recommend", Arrays.asList());
    }

    private List<ActivityIndex> convert2Index(List<Activity> activities) {
        return Lists.transform(activities, new Function<Activity, ActivityIndex>() {
            @Override
            public ActivityIndex apply(Activity activity) {
                ActivityIndex activityIndex = new ActivityIndex();
                activityIndex.setId(activity.getId());
                activityIndex.setTitle(activity.getTitle());
                activityIndex.setSummary(StringUtils.substring(HTMLTagsUtil.delHTMLTag(activity.getDescription()), 0,
                        200) + "...");
                activityIndex.setAvgFee(activity.getAvgFee());
                activityIndex.setPeopleNum(activity.getPeopleNum());
                activityIndex.setPlace(activity.getPlace());
                activityIndex.setSponsor(checkNotNull(userService.selectUserById(activity.getUserId())).getUserName());
                activityIndex.setStartDay(activity.getStartDay());
                activityIndex.setStartHHMM(activity.getStartHHMM());
                activityIndex.setPoster(activity.getPoster());
                return activityIndex;
            }
        });
    }


    /**
     * *
     * bean初始化时建立索引文件 TODO 不合理，主要问题是打开上次索引文件时没有结果
     *
     * @throws java.io.IOException
     */
    @PostConstruct
    public void reIndex() throws IOException {
        long start = System.currentTimeMillis();
        activitySearchService.reIndexAll();
        logger.info("第一次重建索引耗时{}ms", System.currentTimeMillis() - start);
    }
}
